package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.Exception.BizException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;

    /**
     * 新增班级
     * @param clazz
     */
    @Override
    public void insert(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        System.out.println(clazz);
        clazzMapper.insert(clazz);
    }

    /**
     * 查询所有班级
     */
    @Override
    public List<Clazz> selectAll() {
        return clazzMapper.selectAll();
    }

    /**
     * 分页查询
     * @param clazzQueryParam
     * @return
     */
    @Override
    public PageResult page(ClazzQueryParam clazzQueryParam) {
        //1. 设置分页参数
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        List<Clazz> clazzList = clazzMapper.page(clazzQueryParam);
        Page<Clazz> p = (Page<Clazz>) clazzList;
        List<Clazz> result = p.getResult();
        LocalDate now = LocalDate.now();
        for (Clazz clazz : result) {
            if (now.isAfter(clazz.getBeginDate())) {
                clazz.setStatus("已结课");
            } else if (now.isBefore(clazz.getEndDate())) {
                clazz.setStatus("未开课");
            } else {
                clazz.setStatus("在读");
            }
        }
        return new PageResult<>(p.getTotal(), p.getResult());
    }

    /**
     * 根据id查询班级
     * @param id
     * @return
     */
    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getById(id);
    }

    /**
     * 根据id删除班级
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        // 检查班级是否有学生
        Integer exists = studentMapper.existsWithClazzId(id);
        if(exists > 0){
            throw new BizException("该班级下有学生，无法删除");
        }
        clazzMapper.deleteById(id);
    }

    /**
     * 修改班级
     * @param clazz
     */
    @Override
    public void update(Clazz clazz) {
        //补全基础属性
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);

    }
}
